package com.cbs.android.module.shit;

import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;

import com.cbs.android.component.application.CBSService;
import com.cbs.android.component.application.activity.CBSActivity;
import com.cbs.android.component.log.L;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by broche on 29/11/2016.
 */

public class ShitService extends CBSService {
    private static final String TAG = ShitService.class.getName();
    private ShitThread shitThread;
    private MyHandler shitHandler = new MyHandler();

    @Override
    public void onCreate() {
        super.onCreate();
        L.e(TAG, "service.oncreate");
        shitThread = new ShitThread(shitHandler);
        shitThread.start();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        L.e(TAG, "service.onbind");
        if (shitThread == null) {
            return null;
        }
        return new ShitServiceBinder();
    }

    @Override
    public void onDestroy() {
        L.e(TAG, "service.destroy");
        super.onDestroy();
        if (shitThread != null) {
            shitThread.interrupt();
            shitThread = null;
        }
    }

    public class ShitServiceBinder extends Binder {
        public Shit getShit(int shitType, int subjectId) {
            return shitThread.getShit(shitType, subjectId);
        }

        public void deleteShit(int shitType, int subjectId) {
            shitThread.deleteShit(shitType, subjectId);
        }
    }

    private static class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            L.e(TAG, "service.handler");
            List<WeakReference<CBSActivity>> keys2Remove = new ArrayList<>();
            for (WeakReference<CBSActivity> activityWeakReference : ShitModule.getListeners().keySet()) {
                if (activityWeakReference != null && activityWeakReference.get() != null && !activityWeakReference.get().isDestroyed()) {
                    ShitModule.getListeners().get(activityWeakReference).onShitUpdated();
                } else {
                    keys2Remove.add(activityWeakReference);
                }
            }
            for (WeakReference<CBSActivity> key : keys2Remove) {
                ShitModule.getListeners().remove(key);
            }
        }
    }
}
